import json

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login

from django.http import JsonResponse
from django.views import View

from MeiDuo import settings
from apps.cart.utils import merge_cart_cookie_to_redis
from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generate_access_token, check_access_token
from apps.users.models import User


class QQLoginURLView(View):
    def get(self, request):
        # 1使用QQLoginTool.QQtool生成跳转链接
        # 1.1导入
        # from QQLoginTool.QQtool import OAuthQQ
        # 1.2 初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state="perfect")
        # 1.3获取QQ登录扫码页面 扫码后得到Authorization Code
        login_url = oauth.get_qq_url()
        # 2返回响应
        return JsonResponse({"code": 0, "login_url": login_url})


class OauthView(View):
    # /oauth_callback/?code=B05D89158499A4AEE23B4A7AA42ECE65
    def get(self, request):
        # 1.获取code
        code = request.GET.get("code")
        print('code:', code)
        # 2.根据code获取token
        # 2.1导入
        # 2.2初始化OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state="perfect")
        # 2.3调用get_access_token方法获取token
        access_token = oauth.get_access_token(code)
        print("access_token:", access_token)
        # 3.根据token获取openid
        openid = oauth.get_open_id(access_token)
        print('openid:', openid)  # 89F556BED3B4985BB5D364EFAEB760E5

        # 4根据openid去数据库查询OAuthQQUser 账号数据
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)

        except Exception as e:
            print(e)
            # 4.1如果不存在 捕获异常 邹没有绑定的逻辑 绑定页面
            # 前段分析后 返回openid key叫做access_token

            # 对openid加密
            openid = generate_access_token(openid)
            return JsonResponse({"code": 400, "access_token": openid})

        else:
            # 4.2如果存在 正常犯规数据 做登录状态保持
            # session
            login(request, qquser.user)
            # cookie
            response = JsonResponse({"code": 0, "errmsg": "ok"})
            response.set_cookie("username", qquser.user.username)
            return response

    def post(self, request):
        # 1.接收请求
        data_dict = json.loads(request.body.decode())
        # 2.获取请求参数 手机号 密码 短信验证码 openid
        mobile = data_dict.get("mobile")
        password = data_dict.get("password")
        sms_code = data_dict.get("sms_code")
        openid = data_dict.get("access_token")

        # 对openid解密获取原数据
        openid = check_access_token(openid)
        print(openid)

        # 验证参数
        if not all([mobile, password, sms_code, sms_code]):
            return JsonResponse({"code": 400, "errmsg": "请输入完整的信息"})

        # 3.根据手机号 查询是否已经注册
        try:
            user = User.objects.get(mobile=mobile)

        except Exception as e:
            print(e)
            # 5.没有注册 创建一个对象 绑定 用户和openid
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 4.已经注册 密码验证 密码正确 直接绑定 用户和openid
            if not user.check_password(password):
                return JsonResponse({"code": 400, "errmsg": "账号密码不正确"})

        try:
            # 绑定user 和 openid
            OAuthQQUser.objects.create(user=user, openid=openid)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "已经绑定"})

        # 6.状态保持
        login(request, user)
        response = JsonResponse({"code": 0, "errmsg": "ok"})

        response.set_cookie("username", user.username)

        # 登录合并添加购物车
        response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        # 7.返回响应
        return response
